﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Xml;
using Common;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using Model;
using StationClient.Properties;
 

namespace BusStationClient
{
    public unsafe partial class MainForm : Form
    {


        private UdpServer _server;
        
        //private UdpClient _udpClient;
        
        private bool _isListen;
        private GMapOverlay _overLayTaxi;        //出租车图层
        private GMapOverlay _overlayPosition;    //我的位置图层
        private GMapOverlay _overlayPublicPlace; //公共场所图层


        private IPEndPoint _serverPoint;         //服务器地址
        private byte[] _searchBusCommand;        //搜索车辆命令
        private int _updateSleepTime = 10000;    //搜索车辆间隔时间
        private Hashtable TaxiList = Hashtable.Synchronized(new Hashtable()); //车辆列表
        readonly System.Windows.Forms.Timer _timerPerf = new System.Windows.Forms.Timer();

        private DataTable _dtTaxiGpsList = new DataTable(); //车辆GPS信息表
        private double _clientVersion = 1.44d;  //版本号
        
        //private string _strAd = "";  //文字广告  暂未使用
        //readonly System.Windows.Forms.Timer _timerAd = new System.Windows.Forms.Timer();
 
        private bool _isUpdating = false; //是否正在更新版本

        private PointLatLng _myLocation;  //我的位置
 
        private bool _isLinkinternet = true; //网络连接是否正常
        readonly System.Windows.Forms.Timer _timerTimeNow = new System.Windows.Forms.Timer();

        private string _phoneNumeber = "100000000100"; //本机编号

        private DateTime _lastDragTime; //地图最后人为操作时间

        private DataTable _dtGpsList;  //Gps信息表
       
        private string _adImgUrlHost; //广告图片网络地址

        private List<string> _adImageList;//广告图片列表

        private  string _adImgLocalPath = 
            Environment.CurrentDirectory + "\\" + "ADImages\\";

        private Thread _playAdImgs;

        private int _xmlVersionOfmy;
        private int _xmlVersionOfnewest;
        private string _xmlFilePath;

        public MainForm()
        {
            InitializeComponent();

            //axShockwaveFlash1.FlashVars = @"F:\222.flv";
            //axShockwaveFlash1.LoadMovie(0, @"F:\mv.swf");
            //axShockwaveFlash1.Play();

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
              
            // this.TopMost = false; 
            Init();

            double dis = CommonRoutine.GetDistanceBetweenTwoGps(30.471756, 114.419860
                                                                , 30.199146, 115.037155);

 
                


            //Thread threadIniWatchDog = new Thread(IniWatchDog) { IsBackground = true };
            //threadIniWatchDog.Start();

            //广告图片
            Thread initAdImages = new Thread(InitAdImgsList);
            initAdImages.IsBackground = true;
            initAdImages.Start();

            _playAdImgs = new Thread(PlayAdPictures);
            _playAdImgs.IsBackground = true;
            _playAdImgs.Start();

            //Thread threadUdpReceive = new Thread(UdpReceive);
            //threadUdpReceive.IsBackground = true;
            //threadUdpReceive.Start();
            
            Thread thread = new Thread(SendCommandToSearchBus);
            thread.IsBackground = true;
            thread.Start();
         
            Thread threadCompareVersion = new Thread(SendCommandForVersion);
            threadCompareVersion.Start();
            threadCompareVersion.IsBackground = true;
 
            Thread resetMap = new Thread(MapReset);
            resetMap.IsBackground = true;
            resetMap.Start();

            Thread loadPublicPlace = new Thread(LoadPublicPlace);
            loadPublicPlace.IsBackground = true;
            loadPublicPlace.Start();

        }

        

        private void Init()
        {
            #region  初始化 
            string[] iniConfig = OperateConfig.GetStationConfig();
            //Form
            this.WindowState = FormWindowState.Maximized;
            label_version.Text = "V" + _clientVersion.ToString("0.00");
            this.BackgroundImage = new Bitmap("main_bg.png");           
            //Map            
            MainMap.Manager.Mode = AccessMode.ServerAndCache;
            MainMap.MapProvider = GMapProviders.GoogleChinaMap;

            MainMap.ScalePen.Color = Color.Transparent;
            MainMap.CenterPen.Color = Color.Transparent;

            //公共场所图层
            _overlayPublicPlace = new GMapOverlay("PublicPlace");
            MainMap.Overlays.Add(_overlayPublicPlace);
            //出租车图层
            _overLayTaxi = new GMapOverlay("Taxi");
            MainMap.Overlays.Add(_overLayTaxi);
            MainMap.MaxZoom = 18;
            MainMap.MinZoom = 8;          
            zoomTrack.Properties.Maximum = 18;
            zoomTrack.Properties.Minimum = 8;
            int zoom = 14;
            double theCenterLat = 29.24828790;
            double theCenterLng = 115.78491210;
            int.TryParse(iniConfig[8], out zoom);
            double.TryParse(iniConfig[6], out theCenterLat);
            double.TryParse(iniConfig[7], out theCenterLng);
            MainMap.Zoom = zoom;        
            zoomTrack.Value = zoom;
            MainMap.Position = new PointLatLng(theCenterLat, theCenterLng);
            MainMap.DragButton = MouseButtons.Left;
            _myLocation = MainMap.Position;
           
            int.TryParse(iniConfig[2], out _updateSleepTime);
            IPAddress ip = IPAddress.Parse("221.232.148.74");
            int port = ConstParameters.AstPort;
            //int.TryParse(iniConfig[1], out port);
            _serverPoint = new IPEndPoint(ip, port);
            if (iniConfig[5].Trim('\0') != "1")
            {
                TopMost = false;
            }
            string asServerip = iniConfig[0];
             //if(asServerip==)
            bool isIpstr = Regex.IsMatch(asServerip, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
            if (isIpstr)
            {
                ip = IPAddress.Parse(asServerip);
                _serverPoint = new IPEndPoint(ip, port);
            }
            else
            {
                Thread tGetServerIp = new Thread(GetServerIp);
                tGetServerIp.IsBackground = true;
                tGetServerIp.Start(asServerip);                
            }
            if (iniConfig[3].Length == 11)
            {
                _phoneNumeber = "1" + iniConfig[3];
            }

            int.TryParse(iniConfig[9], out _xmlVersionOfmy);

            _searchBusCommand = OperateAgreement.GetNearByTaxisMessageData(
               theCenterLat,theCenterLng,15,_phoneNumeber);            
            // _strAd = iniConfig[4];
            //if (iniConfig[4] != "" && iniConfig[4].Trim().EndsWith("/"))
            //{
            //    _adImgUrlHost = iniConfig[4].Trim();      
            //}
            _adImgUrlHost = "http://www.cityofcar.com:8086/ADImages/";
            _xmlFilePath = "http://www.cityofcar.com:8086/gpsinfos.xml";

            //在线状态及更新时间
            label_newestUpdateTime.Text = "正在获取信息...";
            _isListen = true;
             
            IPAddress[] ipss = Dns.GetHostAddresses(Dns.GetHostName());
            if (ip == null || ipss.Length == 0)
            {
                //获取不到本机IP，程序自动重启。
                Thread thread = new Thread(RestartProgram) { IsBackground = true };
                thread.Start();
            }
             
            _server = new UdpServer( ConstParameters.AstPort);
            _server.OnReceivedData += server_OnDataReceived;
            _server.Start();


            //udpClient udpClient = new UdpClient(ipep);
            //_udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //_udpClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            //_udpClient.Bind(ipep);
            
            //  我的位置信息
            _overlayPosition = new GMapOverlay("MyPosition");
            MainMap.Overlays.Add(_overlayPosition);
            Bitmap obj = Resources.mylocation_50_2;
            //GMapMarker marker = new GMarkerGoogle(new PointLatLng(theCenterLat, theCenterLng),
            //   obj);
            string strMylocation = "";
            if (iniConfig[4] != "智慧城市-出租车智能调度系统")
            {
                strMylocation = iniConfig[4];
            }
            MyLocationMarker marker = new MyLocationMarker(
            new PointLatLng(theCenterLat, theCenterLng), obj, strMylocation);
            marker.Tag = "MyPosition";
            _overlayPosition.Markers.Add(marker);

            string[] pwdConfig = OperateConfig.GetStationPwdConfig();

            int.TryParse(pwdConfig[0], out _exitPassWord);
            int.TryParse(pwdConfig[1], out _setPositionPwd);

            btn_exit.Visible = iniConfig[10] != "0";

            //出租车Gps信息列表
            _dtGpsList = new DataTable();
            _dtGpsList.Columns.Add("Phone");
            _dtGpsList.Columns.Add("Lat");
            _dtGpsList.Columns.Add("Lng");
            _dtGpsList.Columns.Add("Distance", typeof(double));

            _dtTaxiGpsList = _dtGpsList.Copy();
             
            _timerPerf.Tick += DrawTaxisOnMap;
            _timerPerf.Enabled = true;
            _timerPerf.Interval = 1;
            _timerPerf.Start();

            //label_ad.Text = _strAd;
            //_timerAd.Tick += PlayAd;
            //_timerAd.Enabled = true;
            //_timerAd.Interval = 30;
            //_timerAd.Start();

            _timerTimeNow.Tick += ShowTimeNow;
            _timerTimeNow.Enabled = true;
            _timerTimeNow.Interval = 1000;
            _timerTimeNow.Start();
                
            #endregion

           
 
        }

        private void GetServerIp(object asServerip)
        {
            #region  解析服务器IP地址
            while (true)
            {
                try
                {                       
                    IPAddress[] ips = Dns.GetHostAddresses((string)asServerip);
                    IPAddress  ip = ips.Length > 0 ? ips[0] : IPAddress.Parse("219.140.165.6");
                    LogService.WriteDebugLog("解析的" + asServerip + "IP:为" + ip.ToString(), DateTime.Now);
                    if (ips.Length == 0)
                    {
                        Thread.Sleep(2000);
                        LogService.WriteLog(asServerip + "解析域名失败...");
                    }
                    else
                    {
                        _serverPoint = new IPEndPoint(ip, ConstParameters.AstPort);
                        Thread.Sleep(60 * 60 * 1000);    
                    }                      
                }
                catch (Exception ex)
                {
                    Thread.Sleep(2000);
                    LogService.WriteLog(asServerip + "解析域名失败...");
                }
            }
            #endregion
        }
       

        //获取广告图片列表
        private void InitAdImgsList()
        {
            _adImageList = new List<string>();
           // _adImgList = new List<Image>();    
           // string path = Environment.CurrentDirectory + "\\" + "ADImages";
            DirectoryInfo imgDir = new DirectoryInfo(_adImgLocalPath);
            if (!imgDir.Exists)
            {
                Directory.CreateDirectory(_adImgLocalPath);
            }
            FileInfo[] files = imgDir.GetFiles("*.jpg");   //获取文件
            foreach (FileInfo fileInfo in files)
            {
                string name = fileInfo.Name;
                //if (!name.Contains("ad_")) continue;
                
                _adImageList.Add(name);
                //Image img = Image.FromFile(fileInfo.FullName);
                //Bitmap newImg = new Bitmap(img,picBox1.Width,picBox1.Height);
                //_adImgList.Add(newImg);
            }         
        }


        void server_OnDataReceived(object sender, EventArgs e)
        {
            #region  UDP 接收数据
            SocketAsyncEventArgs socketAsyncEventArgs = e as SocketAsyncEventArgs;
            if (socketAsyncEventArgs != null)
            {
                if (socketAsyncEventArgs.BytesTransferred >= ConstParameters.MhLenth)
                {
                    byte[] receDataaaa = new byte[socketAsyncEventArgs.BytesTransferred];
                    Array.Copy(socketAsyncEventArgs.Buffer, 0, receDataaaa, 0, receDataaaa.Length);
                    List<byte> receBufferBb = new List<byte>();
                    receBufferBb.AddRange(receDataaaa);
                    if (receDataaaa.Length > ConstParameters.MhLenth)
                    {

                        int receBufferBBindex = 0;
                        int sendflag = -1;
                        int endindex = 0;
                        List<byte> receByteList = new List<byte>();


                        int packageCount = OperateAgreement.GetPackageCountInMessageHead(receDataaaa);
                        int packageIndex = OperateAgreement.GetPackageIndexInMessageHead(receDataaaa);
                        if (packageIndex==1)
                        {
                            _dtGpsList.Rows.Clear();    
                        }
                        

                        foreach (byte b in receBufferBb)
                        {
                            receBufferBBindex++;
                            if (b == 0x7e) sendflag++;
                            if (sendflag >= 0)
                            {
                                if (sendflag == 0) { receByteList.Add(b); }
                                else if (sendflag == 1)
                                {
                                    receByteList.Add(b);
                                    byte[] receData = receByteList.ToArray();
                                    receByteList.Clear();
                                    sendflag = -1;
                                    endindex = receBufferBBindex;

                                    try
                                    {

                                        byte[] realData = OperateAgreement.RestoreReceData(receData);
                                        if (OperateAgreement.JudgeisCompleteData(realData))
                                        {
                                            ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);

                                            switch (messageId)
                                            {
                                                case ConstParameters.CmdPhoneUserGetNearbyTaxiReply2:
                                                    #region  获取出租车列表
                                                    lock (TaxiList.SyncRoot)
                                                    {                                                    
                                                        Array.Reverse(realData, ConstParameters.MBodySatrtIndex, 2);
                                                        int taxicount = BitConverter.ToInt16(realData, ConstParameters.MBodySatrtIndex);
                                                        for (int i = 0; i < taxicount; i++)
                                                        {
                                                            int startIndex = ConstParameters.MBodySatrtIndex + 2 + i * 45;
                                                            byte[] byteTemp = new byte[5];
                                                            Array.Copy(realData, startIndex, byteTemp, 0, 5);
                                                            string strlng = CommonRoutine.ByteToBcdString(byteTemp);
                                                            double lng = double.Parse(strlng) / Math.Pow(10, 6);
                                                            byteTemp = new byte[5];
                                                            Array.Copy(realData, startIndex + 5, byteTemp, 0, 5);
                                                            string strLat = CommonRoutine.ByteToBcdString(byteTemp);
                                                            double lat = double.Parse(strLat) / Math.Pow(10, 6);
                                                            byteTemp = new byte[4];
                                                            Array.Copy(realData, startIndex + 10, byteTemp, 0, 4);
                                                            IPAddress ip = new IPAddress(byteTemp);
                                                            byte state = realData[startIndex + 14];
                                                            byteTemp = new byte[6];
                                                            Array.Copy(realData, startIndex + 15, byteTemp, 0, 6);
                                                            string phone = CommonRoutine.ByteToBcdString(byteTemp);
                                                            string taxiNo = ASCIIEncoding.GetEncoding("GBK").GetString(
                                                                realData, startIndex + 21, 8);
                                                            string taxiType = ASCIIEncoding.GetEncoding("GBK").GetString(
                                                                realData, startIndex + 29, 12);
                                                            byte star = realData[startIndex + 41];
                                                            short angle = BitConverter.ToInt16(realData, startIndex + 42);//2字节
                                                            byte speed = realData[startIndex + 44];

                                                            TaxiInfo temp = new TaxiInfo();
                                                            temp.Angle = angle;
                                                            temp.DriverPhoneNumber = phone.Remove(0, 1);
                                                            temp.Ip = ip;
                                                            temp.Latitude = lat;
                                                            temp.Longitude = lng;
                                                            temp.Speed = speed;
                                                            temp.TaxiState = state;
                                                            temp.TaxiNo = taxiNo;
                                                            temp.TaxiType = taxiType;
                                                            temp.StartLevel = star;
                                                            temp.UpdateTime = DateTime.Now;
                                                            TaxiList[temp.DriverPhoneNumber] = temp;

                                                            DataRow[] rows = _dtGpsList.Select("Phone ='"
                                                                + temp.DriverPhoneNumber + "'");
                                                            if (rows.Length == 0)
                                                            {
                                                                DataRow dr = _dtGpsList.NewRow();
                                                                dr["Phone"] = temp.DriverPhoneNumber;
                                                                dr["Lat"] = lat;
                                                                dr["Lng"] = lng;
                                                                dr["Distance"] = CommonRoutine.GetDistanceBetweenTwoGps(
                                                                    _myLocation.Lat, _myLocation.Lng, lat, lng);
                                                                _dtGpsList.Rows.Add(dr);
                                                            }
                                                            else
                                                            {
                                                                rows[0]["Lat"] = lat;
                                                                rows[0]["Lng"] = lng;
                                                                rows[0]["Distance"] = CommonRoutine.GetDistanceBetweenTwoGps(
                                                                    _myLocation.Lat, _myLocation.Lng, lat, lng);
                                                            }
                                                        }


                                                        if (packageIndex==packageCount)
                                                        {
                                                            List<GMapMarker> delTaxiMarkers = new List<GMapMarker>();
                                                            foreach (GMapMarker gMapMarker in _overLayTaxi.Markers)
                                                            {
                                                                if (!TaxiList.Contains(gMapMarker.Tag.ToString()))
                                                                {
                                                                    delTaxiMarkers.Add(gMapMarker);
                                                                }
                                                            }

                                                            if (delTaxiMarkers.Count > 0)
                                                            {
                                                                foreach (GMapMarker gMapMarker in delTaxiMarkers)
                                                                {
                                                                    GMapMarker marker = gMapMarker;
                                                                    this.BeginInvoke(new MethodInvoker(() => _overLayTaxi.Markers.Remove(marker)));
                                                                }
                                                                delTaxiMarkers.Clear();
                                                            }

                                                            _dtTaxiGpsList = _dtGpsList.Copy();
                                                            //foreach (DataRow row in _dtGpsList.Rows)
                                                            //{
                                                            //    if (_dtTaxiGpsList.Rows.Count > 0)
                                                            //    {
                                                            //        DataRow[] rows = _dtTaxiGpsList.Select("Phone='"
                                                            //            + row["Phone"] + "'");
                                                            //        if (rows.Length > 0)
                                                            //        {
                                                            //            _dtTaxiGpsList.Rows.Remove(rows[0]);
                                                            //        }
                                                            //    }
                                                            //    _dtTaxiGpsList.Rows.Add(row.ItemArray);
                                                            //}
                                                        }
                                                      

                                                    }
                                                 
                                                    BeginInvoke(new MethodInvoker(() =>
                                                        label_newestUpdateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                                                #endregion
                                                    break;

                                                case ConstParameters.CmdSendADToStation:
                                                    #region 接收广告信息学
                                                    string currentStation = Encoding.GetEncoding("GBK").GetString(realData,
                                                        ConstParameters.MBodySatrtIndex, realData.Length - 19);
                                                   // _strAd = currentStation.Trim('\0');
                                                    #endregion
                                                    break;

                                                case ConstParameters.CmdStationClientVersionReply:
                                                    #region 接收客户端最新版本号
                                                    double newestVersion = BitConverter.ToDouble(
                                                        realData, ConstParameters.MBodySatrtIndex);
                                                    if (newestVersion > _clientVersion)
                                                    {
                                                        if (_isUpdating == false)
                                                        {
                                                            Process.Start(Application.StartupPath + @"\AutoUpdate.exe");
                                                            _isUpdating = true;
                                                        }
                                                        // Environment.Exit(0);                                                     
                                                    }
                                                    #endregion
                                                    break;

                                                case ConstParameters.CmdGetStationAdUrlListReply:
                                                    #region 接收广告图片网络地址

                                                    string imgUrl = Encoding.GetEncoding("GBK").GetString(
                                                        realData,ConstParameters.MBodySatrtIndex,realData.Length - 19);
                                                    if (imgUrl.EndsWith("|"))
                                                    {
                                                        imgUrl = imgUrl.Remove(imgUrl.Length - 1);
                                                        Thread thread = new Thread(HandelAdImages);
                                                        thread.IsBackground = true;
                                                        thread.Start(imgUrl);
                                                    }                                                   
                                                    break;

                                                    #endregion

                                                case ConstParameters.CmdStationGetNewestXmlVersionReply:
                                                    #region 接收xml文件最新版本号

                                                    int version =BitConverter.ToInt32(realData,
                                                        ConstParameters.MBodySatrtIndex);
                                                    if (version>0)
                                                    {
                                                        _xmlVersionOfnewest = version;
                                                        if (_xmlVersionOfnewest > _xmlVersionOfmy)
                                                        {
                                                            Thread updateXml = new Thread(UpdateXmlfile);
                                                            updateXml.IsBackground = true;
                                                            updateXml.Start();
                                                        }
                                                    }                                                                                                        

                                                    #endregion
                                                    break;

                                            }
                                             
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex);
                                    }

                                }
                            }
                        }
                        //--------------------
                        //if (_dtTaxiGpsList.Rows.Count == 0)
                        //{
                        //    _dtTaxiGpsList = _dtGpsList.Copy();
                        //}

                      


                        if (endindex > 0)
                        {
                            receBufferBb.RemoveRange(0, endindex);
                        }
                    }
                }
            }
            #endregion
        }
 
        private void ShowTimeNow(object sender, EventArgs e)
        {
            #region 显示当期时间

            label_timeNow.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            #endregion
        }
         
        private void DrawTaxisOnMap(object sender, EventArgs e)
        {
            #region 画出租车车
            try
            {
                TaxiInfo temp = new TaxiInfo();
                lock (TaxiList.SyncRoot)
                {
                    foreach (TaxiInfo taxiInfo in TaxiList.Values)
                    {
                        temp = taxiInfo;
                        break;
                    }

                    if (temp != null && temp.DriverPhoneNumber != null)
                    {
                        lock (_overLayTaxi.Markers)
                        {
                            lock (TaxiList.SyncRoot)
                            {
                                TaxiList.Remove(temp.DriverPhoneNumber);
                            }
                            GMapMarker g =
                                _overLayTaxi.Markers.FirstOrDefault(
                                    gMapMarker => gMapMarker.Tag.ToString() == temp.DriverPhoneNumber);
                            if (g != null)
                            {
                                this.BeginInvoke(new MethodInvoker(() => _overLayTaxi.Markers.Remove(g)));
                            }
                            PointLatLng pointLatLng = new PointLatLng(temp.Latitude, temp.Longitude);
                            Bitmap obj = GetTaxiBitmapByAngle(temp.Angle);
                            long phone = 10000000000;
                            long.TryParse(temp.DriverPhoneNumber,out phone);
                            string strphone = phone.ToString("000-0000-0000");
                            string strTip = temp.TaxiNo + "\r\n" +strphone ;
                            BusMarker gMarker = new BusMarker(pointLatLng, obj, strTip)
                            {
                                ToolTipText =
                                    "司机手机号：" + temp.DriverPhoneNumber +
                                    Environment.NewLine
                                    + "车牌号码：" + temp.TaxiNo +
                                    Environment.NewLine
                                    + "出租车型号：" + temp.TaxiType +
                                    Environment.NewLine
                                    + "更新时间：" +
                                    temp.UpdateTime.ToString("HH:mm:ss") +
                                    Environment.NewLine
                                ,                                
                                ToolTipMode = MarkerTooltipMode.OnMouseOver,
                                Tag = temp.DriverPhoneNumber
                            };
                            gMarker.ToolTip.Format.Alignment = StringAlignment.Near;
                            this.BeginInvoke(new MethodInvoker(() => _overLayTaxi.Markers.Add(gMarker)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogService.WriteLog("DrawBusOnMap 异常"+ex.Message);
            }
          
            #endregion
        }

        private void SendCommandToSearchBus()
        {
            #region 发送搜车命令
            while (_isListen)
            {
                if (TaxiList.Count == 0)
                {
                    try
                    {
                        if (TestIsLinkInternet())
                        {
                            linkInternetDt = DateTime.Now;
                        }
                        TimeSpan timeSpan = DateTime.Now - linkInternetDt;
                        if (timeSpan.TotalSeconds > 600)
                        {
                            _isLinkinternet = false;
                            LogService.WriteDebugLog(" _isLinkinternet = false;", DateTime.Now);
                        }
                        else
                        {
                            _isLinkinternet = true;
                        }

                        _clickTick++;
                        if (_clickTick % 5 == 0)
                        {
                            _clickTick = 0;
                            BeginInvoke(new MethodInvoker(() =>
                                MainForm_Click(null, null)));

                        }
                        string strComnd = "搜车命令："+Environment.NewLine;
                        foreach (byte bb in _searchBusCommand)
                        {
                            strComnd += bb.ToString("x2")+" ";
                        }
                        Console.WriteLine(strComnd);
                       // _udpClient.Send(_searchBusCommand, _searchBusCommand.Length, _serverPoint);
                        _server.SendData(_searchBusCommand, _serverPoint);

                        //_dtTaxiGpsList.Rows.Clear();

                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(30000);
                        LogService.WriteLog("SendCommandToSearchBus异常："+ex.Message);
                    }
                }
                Thread.Sleep(_updateSleepTime);
            }
            #endregion
        }

        private int _clickTick;
        private DateTime linkInternetDt = DateTime.Now;
        private void SendCommandForVersion()
        {
            #region 发送查询版本号命令
            //byte[] data = OperateAgreement.GetEmptyBodyMessageData(
            //    ConstParameters.CmdStationGetClientVersion, _phoneNumeber);

            //byte[] messageBody = BitConverter.GetBytes(_clientVersion);
            //byte[] phoneBytes = CommonRoutine.BcdStringToBytes(_phoneNumeber);
            //byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdStationGetClientVersionWithCurrentVersion,
            // false, false, messageBody.Length,phoneBytes, new byte[2],
            //                                     1, 1);
            //List<byte> messageDatas = new List<byte>();
            //messageDatas.AddRange(OperateAgreement.PackageSendData(messageHead, messageBody.ToArray()));
            //byte[] data = messageDatas.ToArray();
            byte[] data = OperateAgreement.GetStationVersionData(
                _clientVersion, _phoneNumeber);

            byte[] dataForAd = OperateAgreement.GetEmptyBodyMessageData(
              ConstParameters.CmdGetStationAdUrlList, _phoneNumeber);

            byte[] dataXmlVersion = OperateAgreement.GetStationXmlVersion(
                _xmlVersionOfmy, _phoneNumeber);

            while (_isListen)
            {
                Thread.Sleep(1000*70); 
                try
                {
                    //_udpClient.Send(data, data.Length, _serverPoint);
                    _server.SendData(data, _serverPoint);
                    Thread.Sleep(3000);
                    _server.SendData(dataForAd, _serverPoint);

                    Thread.Sleep(3000);
                    _server.SendData(dataXmlVersion,_serverPoint);
                }
                catch (Exception ex)
                {
                    LogService.WriteLog("发送查询版本号失败：" + ex.Message);
                    Thread.Sleep(60000);
                }

                Thread.Sleep(60 * 60 * 1000);
            }
            #endregion
        }
 
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
           // _udpClient.Close();
        }

        private void MainMap_MouseClick(object sender, MouseEventArgs e)
        {
            
            if (e.Button == MouseButtons.Right)
            {
                PointLatLng p = MainMap.FromLocalToLatLng(e.X, e.Y);
                label1.Text = p.Lat.ToString();
                label2.Text = p.Lng.ToString();                                
            }
            if(_isSetModel)
            {
                PointLatLng p = MainMap.FromLocalToLatLng(e.X, e.Y);
                GMapMarker g = _overlayPosition.Markers.FirstOrDefault(
                 gMapMarker => gMapMarker.Tag.ToString() == "MyPosition");
                if (g != null)
                {
                  g.Position = p;   
                }
            }
        }

        public static Bitmap GetTaxiBitmapByAngle(int angle)
        {
            #region  根据方向返回公交车图标
            int two;
            if ((angle >= 0 && angle <= 20) || (angle >= 340 && angle <= 360))
            {
                two = 1;
            }
            else if (angle > 20 && angle < 70)
            {
                two = 2;
            }
            else if (angle >= 70 && angle <= 110)
            {
                two = 3;
            }
            else if (angle > 110 && angle < 160)
            {
                two = 4;
            }
            else if (angle >= 160 && angle <= 200)
            {
                two = 5;
            }
            else if (angle > 200 && angle < 250)
            {
                two = 6;
            }
            else if (angle >= 250 && angle <= 290)
            {
                two = 7;
            }
            else if (angle > 290 && angle < 340)
            {
                two = 8;
            }
            else
            {
                two = 9;
            }
            string name = "_0" + two+"4";
            return (Bitmap)Resources.ResourceManager.GetObject(name);
            #endregion
        }
 
        private void PlayAd(object sender, EventArgs e)
        {
            #region 播放文字广告
            //try
            //{
            //    if (label_ad.Text != _strAd)
            //    {
            //        label_ad.Text = _strAd;
            //        label_ad.Location = new Point(splitContainer1.Panel2.Location.X
            //           + splitContainer1.Panel2.Width, label_ad.Location.Y);
            //    }

            //    if (label_ad.Location.X > splitContainer1.Panel2.Location.X - label_ad.Width)
            //    {
            //        label_ad.Location = new Point(label_ad.Location.X - 2, label_ad.Location.Y);
            //    }
            //    else
            //    {
            //        label_ad.Location = new Point(splitContainer1.Panel2.Location.X
            //            + splitContainer1.Panel2.Width, label_ad.Location.Y);
            //    }
            //}
            //catch (Exception ex)
            //{
            //   LogService.WriteLog("播放广告异常："+ex.Message);
            //}
           
            #endregion
        }


        private void HandelAdImages(object objAdimgUrl)
        {
            #region 处理广告图片

            string newAdUrl = objAdimgUrl.ToString();
            string[] newImgList = newAdUrl.Split('|');
            int existImgCount = 0;
            int succeedDownCount = 0;
            List<string> failedDownList = new List<string>();

            try
            {
                //对比当前广告列表和服务器获取的广告列表 
                foreach (string img in newImgList)
                {
                    //若当前列表中已存在 则不做处理
                    if (_adImageList.Contains(img))
                    {
                        existImgCount++;
                        continue;
                    }
                    //当前没有该图，则下载
                    bool flag = false;
                    for (int i = 0; i < 5; i++)
                    {
                        flag = CommonRoutine.DownloadFileByUrl(
                            _adImgUrlHost + img, _adImgLocalPath + img);
                        if (flag)
                        {
                            succeedDownCount++;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        failedDownList.Add(img);
                    }
                }
                Console.WriteLine("最新广告图片总数为" + newImgList.Length
                    + "    本地已存在" + existImgCount + "张   "
                    + "成功下载" + succeedDownCount + "张");

                if (existImgCount + succeedDownCount == newImgList.Length)
                {
                    Console.WriteLine("=========图片更新成功！=========");
                    List<string> delList = new List<string>();
                    lock (_adImageList)
                    {
                        foreach (string imgName in _adImageList)
                        {
                            if (!newImgList.Contains(imgName))
                            {
                                delList.Add(imgName);
                            }
                        }
                        _adImageList.Clear();
                        //BeginInvoke(new MethodInvoker(() =>
                        //    {
                        //        picBox1.Image.Dispose();
                        //        picBox2.Image.Dispose();        
                        //    }));
                        // _playAdImgs.Abort();
                        Thread.Sleep(1000);
                        _adImageList.AddRange(newImgList);
                        _currentAdImgIndex = 0;
                    }
                    Thread.Sleep(180*1000);
                    foreach (string img in delList)
                    {
                        string imgPath = _adImgLocalPath + img;
                        if (File.Exists(imgPath))
                        {
                            File.Delete(imgPath);
                        }
                    }
                    // _playAdImgs.Start();
                }  
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            #endregion
        }

        private void UpdateXmlfile()
        {
            #region 更新XML文件
            bool flag = false;
            for (int i = 0; i < 5; i++)
            {
                flag = CommonRoutine.DownloadFileByUrl(
                _xmlFilePath, Environment.CurrentDirectory + "\\" + "gpsinfos.xml");
                if (flag)
                {                     
                    break;
                }
                Thread.Sleep(1000*10);
            }
            if (flag)
            {
                //更新本地配置文件中的版本号 清空地图上的图标 重画
                _xmlVersionOfmy = _xmlVersionOfnewest;
                OperateConfig.SaveStationXmlConfig(_xmlVersionOfnewest.ToString());
                BeginInvoke(new MethodInvoker(() => 
                    _overlayPublicPlace.Markers.Clear()));
                Thread.Sleep(3000);
                LoadPublicPlace();
            }
            #endregion
        }

        #region  播放图片广告

       // private List<Image> _adImgList;
        private int _currentAdImgIndex;

        private void PlayAdPictures()
        {
            try
            {
                //while (_adImgList == null)
                while (_adImageList == null)
                {
                    Thread.Sleep(1000);
                }
                ShiftAdPictures();
                while (true)
                {
                    Thread.Sleep(50);
                    if (picBox2.Location.Y > picBox1.Location.Y)
                    {
                        BeginInvoke(new MethodInvoker(() =>
                            picBox2.Location = new Point(picBox2.Location.X, picBox2.Location.Y - 1)));

                    }
                    else
                    {
                        ShiftAdPictures();
                        BeginInvoke(new MethodInvoker(() =>
                        picBox2.Location = new Point(picBox1.Location.X,
                            picBox1.Location.Y + picBox1.Height)));
                        Thread.Sleep(8000);
                    }
                }

            }
            catch (Exception ex)
            {
                
            }
          
                    
        }
        private void ShiftAdPictures()
        {
            try
            {
                //if (_adImgList.Count == 0) return;
                if (_adImageList.Count == 0) return;
                if (_currentAdImgIndex == 0)
                {
                    
                    Image imgone = Image.FromFile(_adImgLocalPath+_adImageList[0]);
                    Bitmap newImgone = new Bitmap(imgone, picBox1.Width, picBox1.Height);                    
                    picBox1.Image = newImgone;                      
                    //判断是否只有一张图
                    if (_adImageList.Count > 1)
                    {
                        Image imgtwo = Image.FromFile(_adImgLocalPath + _adImageList[1]);
                        Bitmap newImgtwo = new Bitmap(imgtwo, picBox1.Width, picBox1.Height);
                        picBox2.Image = newImgtwo;                        
                        _currentAdImgIndex = 1;
                    }
                    else
                    {
                        picBox2.Image = newImgone;                        
                    }               
                }
                else
                {                  
                    //不为最后一张图
                    if (_currentAdImgIndex < _adImageList.Count - 1)
                    {
                        Image imgone = Image.FromFile(
                            _adImgLocalPath +
                            _adImageList[_currentAdImgIndex]);
                        Bitmap newImgone = new Bitmap(imgone, picBox1.Width, picBox1.Height);
                        Image imgtwo = Image.FromFile(
                            _adImgLocalPath +
                            _adImageList[_currentAdImgIndex+1]);
                        Bitmap newImgtwo = new Bitmap(imgtwo, picBox1.Width, picBox1.Height);

                        picBox1.Image = newImgone;
                        picBox2.Image = newImgtwo;                         
                        _currentAdImgIndex++;
                    }
                    else // 最后一张
                    {
                        Image imgone = Image.FromFile(
                           _adImgLocalPath +
                           _adImageList[_currentAdImgIndex]);
                        Bitmap newImgone = new Bitmap(imgone, picBox1.Width, picBox1.Height);
                        Image imgtwo = Image.FromFile(
                            _adImgLocalPath +
                            _adImageList[0]);
                        Bitmap newImgtwo = new Bitmap(imgtwo, picBox1.Width, picBox1.Height);


                        picBox1.Image = newImgone;
                        picBox2.Image = newImgtwo;                        
                        _currentAdImgIndex = 0;
                    }

                
                }
            }
            catch (Exception ex)
            {
                LogService.WriteLog("ShiftAdPictures:"+ex.Message);
            }
          
        }
        #endregion

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
           // _udpClient.Close();
        }
 
        private bool TestIsLinkInternet()
        {
            #region 检测网络连接
            try
            {
                Ping pingSender = new Ping();
                string strIP = "www.baidu.com";          //要ping的IP地址     第一种方法本人亲自试验过。可以使用
                PingOptions pingOption = new PingOptions();
                pingOption.DontFragment = true;

                string data = "sendData:g";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 120;
                PingReply reply = pingSender.Send(strIP, timeout, buffer);
                if (reply.Status == IPStatus.Success)
                {
                    Console.WriteLine("能ping通");
                    LogService.WriteDebugLog("能ping通", DateTime.Now);
                    return true;
                }
                else
                {
                    LogService.WriteDebugLog("不能ping通", DateTime.Now);

                    Console.WriteLine("不能ping通");
                    return false; 
                }
            }
            catch (Exception ex)
            {
                LogService.WriteDebugLog("不能ping通     " + ex.Message, DateTime.Now);

                Console.WriteLine("不能ping通");
                return false;
            }
            #endregion
        }
         
        private void MapReset()
        {
            #region   重置地图焦点 并附近的车型缩放地图比例
 
            Thread.Sleep(5000);
            while (true)
            {
                TimeSpan span = DateTime.Now - _lastDragTime;
                if (span.TotalSeconds < 30)
                {
                    continue;
                }
                lock (_dtTaxiGpsList)
                {
                                    
                DataTable dtTemp = new DataTable();                 
                if(_dtTaxiGpsList.Rows.Count>0)
                 {
                    _dtTaxiGpsList.DefaultView.Sort = "Distance ASC";
                    dtTemp = _dtTaxiGpsList.DefaultView.ToTable();     
                 }
                //先聚焦    
                BeginInvoke(new MethodInvoker(() =>
                {                    
                    MainMap.Position = new PointLatLng(_myLocation.Lat, _myLocation.Lng);
                }));
                Thread.Sleep(500);                
                if (dtTemp.Rows.Count == 0)
                {
                    // 无出租车
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        MainMap.Zoom = 17;                                               
                    }));
                    Thread.Sleep(4000);
                    continue;
                }
                #region 根据附近车辆缩放地图
                double maxLat = double.Parse(dtTemp.Rows[0]["Lat"].ToString());
                double mixLat = double.Parse(dtTemp.Rows[0]["Lat"].ToString());
                double maxLng = double.Parse(dtTemp.Rows[0]["Lng"].ToString());
                double mixLng = double.Parse(dtTemp.Rows[0]["Lng"].ToString());
                for (int i = 0; i < dtTemp.Rows.Count; i++)
                {
                    if (i < 5)
                    {
                        DataRow drTemp = dtTemp.Rows[i];
                        double lat = double.Parse(drTemp["Lat"].ToString());
                        double lng = double.Parse(drTemp["Lng"].ToString());
                        if(lat>maxLat)
                        {
                            maxLat = lat;
                        }
                        if(lat<mixLat)
                        {
                            mixLat = lat;
                        }
                        if(lng>maxLng)
                        {
                            maxLng = lng;
                        }
                        if(lng<mixLng)
                        {
                            mixLng = lng;
                        }
                    }
                    else
                    {
                        break;
                    }
                }                
                bool isOut = false;            
                for (int i = 0; i < 12; i++)
                {
                    double lowLat = MainMap.ViewArea.LocationRightBottom.Lat;
                    double upperLat = MainMap.ViewArea.LocationTopLeft.Lat;
                    double lowLng = MainMap.ViewArea.LocationTopLeft.Lng;
                    double upperLng = MainMap.ViewArea.LocationRightBottom.Lng;
                    if(mixLat<lowLat||maxLat>upperLat||
                        mixLng<lowLng||maxLng>upperLng)
                    {
                        BeginInvoke(new MethodInvoker(() =>
                            {
                                MainMap.Zoom = MainMap.Zoom - 1;
                            }));
                        Thread.Sleep(500);
                        isOut = true;
                        continue;
                    }
                    if(!isOut)
                    {
                        if (mixLat > lowLat && maxLat < upperLat &&
                            mixLng > lowLng && maxLng < upperLng)
                        {
                            BeginInvoke(new MethodInvoker(() =>
                            {
                                MainMap.Zoom = MainMap.Zoom + 1;
                            }));
                        }
                        Thread.Sleep(500);                         
                    }

                }
                 #endregion
                }

                #region   按距离缩放
                //DataRow row;
                //if (dtTemp.Rows.Count <= 5)
                //{
                //    //不超过五辆车  按最后一辆计算
                //    row = dtTemp.Rows[dtTemp.Rows.Count - 1];
                //}
                //else
                //{
                //    //超过五辆按第五辆计算
                //    row = dtTemp.Rows[4];
                //}
                //double distance = double.Parse(row["Distance"].ToString());
                //int zoom;
                //if (distance<=190)
                //{
                //    zoom = 18;
                //}
                //else if(distance>190 && distance<=380)
                //{
                //    zoom = 17;
                //}
                //else if (distance > 380 && distance <= 840)
                //{
                //    zoom = 16;
                //}
                //else if (distance > 840 && distance <= 1500)
                //{
                //    zoom = 15;
                //}
                ////else if (distance > 1386 && distance <= 2700)
                ////{
                ////    zoom = 14;
                ////}
                //else
                //{
                //    zoom = 14;
                //}
                //BeginInvoke(new MethodInvoker(() =>
                //{
                //    MainMap.Zoom = zoom;  
                //    MainMap.Position = new PointLatLng(_myLocation.Lat,_myLocation.Lng);
                //}));

                #endregion

                _dtTaxiGpsList.Rows.Clear();
                Thread.Sleep(30000);
            }
            #endregion
        }

        //重启程序
        private void RestartProgram()
        {
            Thread.Sleep(8000);
            Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
            Environment.Exit(0);
        }

        private void MainMap_OnMapZoomChanged()
        {
            _lastDragTime = DateTime.Now;
            zoomTrack.Value = (int) MainMap.Zoom;
        }
         
        private void zoomTrack_EditValueChanged(object sender, EventArgs e)
        {
            MainMap.Zoom = zoomTrack.Value;
        }
       
        private void MainMap_OnMapDrag()
        {           
            _lastDragTime = DateTime.Now;           
        }

        #region  后台管理：退出程序、重置本地位置
        private void MainForm_Click(object sender, EventArgs e)
        {
            this.Focus();
            int x = Cursor.Position.X;
            int y = Cursor.Position.Y;
            label1.Text = x.ToString();
            label2.Text = y.ToString();
            CheckPassword(x, y);           
        }

        private string _pwdInt = "0";
        private int _exitPassWord = 5;
        private int _setPositionPwd = 174;
        private bool _isSetModel;


        private void CheckPassword(int x, int y)
        {
            //int width = Screen.PrimaryScreen.Bounds.Width;
            //int height = Screen.PrimaryScreen.Bounds.Height;

            #region  本机位置  
            // if (x >= 868 && x <= 943 && y >= 10 && y <= 66)
            //{
            //    _pwdInt += "0";
            //}
            ////键入1                       
            //else if (x >= 1073 && x <= 1150 && y >= 10 && y <= 66)
            //{
            //    _pwdInt += "1";
            //}
            ////提交
            //else if (x >= 506 && x <= 695 && y >= 10 && y <= 66)
            //{
            #endregion

            //键入0
            if (x >= 780 && x <= 839 && y >= 14 && y <= 80)
            {
                _pwdInt += "0";
            }
            //键入1                       
            else if (x >= 954 && x <= 1020 && y >= 14 && y <= 80)
            {
                _pwdInt += "1";
            }
            //提交
            else if (x >= 445 && x <= 618 && y >= 20 && y <= 78)
            {
           
                int pwd = Convert.ToInt32(_pwdInt, 2);
                //退出程序
                if (pwd == _exitPassWord)
                {
                    this.Close();
                }
                //重置站点位置
                if(pwd==_setPositionPwd)
                {
                    _isSetModel = true;
                    btn_SetPosition.Visible = true;
                    btn_cancelSet.Visible = true;
                }
                _pwdInt = "0";
            }
            else//其它重置
            {
                _pwdInt = "0";
            }
        }

        private void btn_SetPosition_Click(object sender, EventArgs e)
        {
           GMapMarker g = _overlayPosition.Markers.FirstOrDefault(
           gMapMarker => gMapMarker.Tag.ToString() == "MyPosition");
            if (g != null)
            {
                _myLocation = g.Position;
                string[] config ={_myLocation.Lat.ToString(),
                                    _myLocation.Lng.ToString()};
                OperateConfig.SaveStationPosition(config);
                MessageBox.Show("本站位置重置成功！");
                _isSetModel = false;
                btn_cancelSet.Visible = false;
                btn_SetPosition.Visible = false;    
            }
        }

        private void btn_cancelSet_Click(object sender, EventArgs e)
        {
            btn_cancelSet.Visible = false;
            btn_SetPosition.Visible = false;
            _isSetModel = false;
        
            GMapMarker g = _overlayPosition.Markers.FirstOrDefault(
             gMapMarker => gMapMarker.Tag.ToString() == "MyPosition");
            if (g != null)
            {
                g.Position = _myLocation;              
            }
        }
        #endregion

        private void LoadPublicPlace()
        {
            #region 加载公共场所xml文件 在地图上画出
            try
            {
                //
                DataSet ds = CXmlFileToDataSet("gpsinfos.xml");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string type = dr["type"].ToString();
                    string name = dr["name"].ToString();
                    double lat = double.Parse(dr["lat"].ToString());
                    double lng = double.Parse(dr["lng"].ToString());
                    double distance = CommonRoutine.GetDistanceBetweenTwoGps(
                        _myLocation.Lat, _myLocation.Lng, lat, lng);
                    if (distance>5000)
                    {
                        continue;
                    }
                    string introduction = dr["introduce"].ToString();
                    string tel = dr["tel"].ToString();
                    Bitmap obj = Resources.overlay_else;
                    switch (type)
                    {
                        //case "住宿":
                        //    obj = Resources.overlay_restaurant;
                        //    break;
                        case "餐饮":
                            obj = Resources.overlay_eatDrank;
                            break;
                        case "酒店":
                            obj = Resources.overlay_restaurant;
                            break;
                        case "加油站":
                            obj = Resources.overlay_gas;
                            break;
                        case "银行":
                            obj = Resources.overlay_bank;
                            break;
                        case "超市":
                            obj = Resources.overlay_market;
                            break;
                        case "娱乐":
                            obj = Resources.overlay_play;
                            break;
                        case "公园":
                            obj = Resources.overlay_park;
                            break;
                        case "医院":
                            obj = Resources.overlay_hospital;
                            break;
                        default:
                            obj = Resources.overlay_else;
                            break;
                    }
                    PlaceMarker marker = new PlaceMarker(
                        new PointLatLng(lat, lng), obj, name);
                    marker.ToolTipText = name + Environment.NewLine +
                        "电话：" + tel + Environment.NewLine +
                        "介绍：" + introduction;
                    marker.ToolTip.Format.Alignment = StringAlignment.Near;
                    marker.ToolTipMode = MarkerTooltipMode.OnMouseOver;
                    marker.Tag = dr;
                    marker.IsVisible = false;
                    _overlayPublicPlace.Markers.Add(marker);
                }
            }
            catch (Exception ex)
            {
                LogService.WriteLog("LoadPublicPlace:" + ex.Message);
            }
            #endregion
        }

        public static DataSet CXmlFileToDataSet(string xmlFilePath)
        {
            #region 读取xml文件返回 dataset
            if (!string.IsNullOrEmpty(xmlFilePath))
            {
                string path = xmlFilePath;
                StringReader StrStream = null;
                XmlTextReader Xmlrdr = null;
                try
                {
                    XmlDocument xmldoc = new XmlDocument();
                    //根据地址加载Xml文件
                    xmldoc.Load(path);

                    DataSet ds = new DataSet();
                    //读取文件中的字符流
                    StrStream = new StringReader(xmldoc.InnerXml);
                    //获取StrStream中的数据
                    Xmlrdr = new XmlTextReader(StrStream);
                    //ds获取Xmlrdr中的数据
                    ds.ReadXml(Xmlrdr);
                    return ds;
                }
                catch (Exception e)
                {
                    LogService.WriteLog("CXmlFileToDataSet异常：" + e.Message);
                    throw e;
                }
                finally
                {
                    //释放资源
                    if (Xmlrdr != null)
                    {
                        Xmlrdr.Close();
                        StrStream.Close();
                        StrStream.Dispose();
                    }
                }
            }
            else
            {
                return null;
            }
            #endregion
        }

        #region  公共场所向导
        private void listView_PlaceType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                listBox_place.Items.Clear();
                int count = listView_PlaceType.SelectedItems.Count;
                if (count < 1)
                {
                    foreach (GMapMarker g in _overlayPublicPlace.Markers)
                    {
                        g.IsVisible = false;
                    }
                    listBox_place.Items.Add("<< 返回我的位置");
                    return;
                }
                string seltType = listView_PlaceType.SelectedItems[0].Text;
                foreach (GMapMarker g in _overlayPublicPlace.Markers)
                {
                    DataRow row = g.Tag as DataRow;
                    string strtype = row["type"].ToString();
                    string strName = row["name"].ToString();
                    if (strtype == seltType)
                    {
                        g.IsVisible = true;
                        listBox_place.Items.Add(strName);
                    }
                    else
                    {
                        g.IsVisible = false;
                    }
                }
                listBox_place.Items.Add("<< 返回我的位置");
            }
            catch (Exception ex)
            {
                LogService.WriteLog("listView_PlaceType_SelectedI:" + ex.Message);
            }
         
        }

        private void listBox_place_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                _lastDragTime = DateTime.Now;
                int index = listBox_place.SelectedIndex;
                if (index == -1) return;
                string name = listBox_place.Items[index].ToString();
                if (name == "<< 返回我的位置")
                {
                    MainMap.Position = _myLocation;
                }
                GMapMarker g = _overlayPublicPlace.Markers.FirstOrDefault(
                 gMapMarker => ((DataRow)gMapMarker.Tag)["name"].ToString()
                     == name);
                if (g != null)
                {
                    MainMap.Position = g.Position;
                }
            }
            catch (Exception ex)
            {
                LogService.WriteLog("listBox_place_Selected:" + ex.Message);
            }
        }
        #endregion



        #region  WatchDog -未使用

        [DllImport("kernel32.dll")]
        private extern static IntPtr LoadLibrary(String DllName);

        [DllImport("kernel32.dll")]
        private extern static IntPtr GetProcAddress(IntPtr hModule, String ProcName);

        [DllImport("kernel32")]
        private extern static bool FreeLibrary(IntPtr hModule);

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        private delegate bool InitializeWinIoType();

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        private delegate bool GetPortValType(UInt16 PortAddr, UInt32* pPortVal, UInt16 Size = 1);

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        private delegate bool SetPortValType(UInt16 PortAddr, UInt32 PortVal, UInt16 Size = 1);

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        private delegate bool ShutdownWinIoType();

        IntPtr hMod;
      

       
        private void IniWatchDog()
        {

            Thread.Sleep(30000);
            if (IntPtr.Size == 4)
            {
                hMod = LoadLibrary("WinIo32.dll");
            }
            else if (IntPtr.Size == 8)
            {
                hMod = LoadLibrary("WinIo64.dll");
            }

            if (hMod == IntPtr.Zero)
            {
                Thread thread = new Thread(RestartProgram) { IsBackground = true };
                thread.Start();

                MessageBox.Show("Can't find WinIo dll.\nMake sure the WinIo library files are located in the same directory as your executable file.", "DumpPort", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            IntPtr pFunc = GetProcAddress(hMod, "InitializeWinIo");

            if (pFunc != IntPtr.Zero)
            {
                InitializeWinIoType InitializeWinIo = (InitializeWinIoType)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(InitializeWinIoType));
                bool Result = InitializeWinIo();

                if (!Result)
                {
                    Thread thread = new Thread(RestartProgram) { IsBackground = true };
                    thread.Start();
                    MessageBox.Show("Error returned from InitializeWinIo.\nMake sure you are running with administrative privileges and that the WinIo library files are located in the same directory as your executable file.", "DumpPort", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    FreeLibrary(hMod);
                }
            }
            Active();
            while (true)
            {
                // 网络连接正常时 执行喂狗
                if (_isLinkinternet)
                {
                    LogService.WriteDebugLog("FeedDog", DateTime.Now);
                    Active();
                }
                else
                {
                    try
                    {
                        ProcessStartInfo ps = new ProcessStartInfo();
                        ps.FileName = "shutdown.exe";
                        ps.Arguments = "-r -t 1";
                        Process.Start(ps);
                    }
                    catch (Exception ex)
                    {
                        LogService.WriteDebugLog("FeedDog-shutdown" + ex.Message, DateTime.Now);
                    }
                }

                Thread.Sleep(180000);
            }

        }

        private void Active()
        {
            IntPtr pFunc = GetProcAddress(hMod, "SetPortVal");
            SetPortValType SetPortVal = (SetPortValType)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(SetPortValType));
            //IntPtr pFunc = GetProcAddress(hMod, "GetPortVal");
            IntPtr pFunc2 = GetProcAddress(hMod, "GetPortVal");
            GetPortValType GetPortVal = (GetPortValType)Marshal.GetDelegateForFunctionPointer(pFunc2, typeof(GetPortValType));
            //write 87h,01h,55h,55h to the index 2eh for enter the MB PnP mode ,enter superio
            SetPortVal(0x2e, 0x87);
            SetPortVal(0x2e, 0x01);
            SetPortVal(0x2e, 0x55);
            SetPortVal(0x2e, 0x55);
            //set logical device number to index 07h
            SetPortVal(0x2e, 0x07);
            SetPortVal(0x2f, 0x07);
            SetPortVal(0x2e, 0x73);	//复位方式   不使用中断方式
            SetPortVal(0x2f, 0xf1);
            SetPortVal(0x2e, 0x72);
            SetPortVal(0x2f, 0xc0);	//按秒计时
            SetPortVal(0x2e, 0x02);
            SetPortVal(0x2f, 0x02);
            //int_timeout = int_secs;
            //byte timeout = 20;		//启动WDT  ACTIVE
            //SetPortVal(0x73, 0x2e);
            //SetPortVal(timeout, 0x2f);
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            Close();
        }


    }

}
